package com.jd.tuning.jvm.lock.reen;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 */
public class ReentrantLockTest3 {

    private ReentrantLock lock=new ReentrantLock();
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();


    /**
     * 操作conditon的代码一定要在lock和unlock之间
     */
    public void awaitCondition1(){
        String threadName=Thread.currentThread().getName();
        try{
            lock.lock();
            System.out.println("awaitCondition1:"+Thread.currentThread().getName());
            //阻塞注册了condition1的线程
            condition1.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }


    public void awaitCondition2(){
        String threadName=Thread.currentThread().getName();
        try{
            lock.lock();
            System.out.println("awaitCondition2:"+Thread.currentThread().getName());
            //阻塞注册了condition1的线程
            condition2.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void signalCondition1(){
        try{
            lock.lock();
            System.out.println("唤醒:"+Thread.currentThread().getName());
            //唤起
            condition1.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void signalCondition2(){
        try{
            lock.lock();
            System.out.println("唤醒:"+Thread.currentThread().getName());
            //唤起
            condition2.signalAll();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ReentrantLockTest3 t=new ReentrantLockTest3();
        new Thread(t::awaitCondition1).start();
        new Thread(t::awaitCondition2).start();
        Thread.sleep(1000L);
        t.signalCondition1();;
        Thread.sleep(1000L);
        t.signalCondition2();
    }
}
